package com.zhangwei.fileuploadbootstarter.service;


import cn.hutool.core.io.FileUtil;

import com.zhangwei.fileuploadbootstarter.domain.FileProperties;
import com.zhangwei.fileuploadbootstarter.domain.FileResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Auther: legion
 * @Date: 2021/10/15 11:15
 * @Description:
 */
public class FileService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private FileProperties properties;

    public FileService(FileProperties properties) {
        this.properties = properties;
        logger.info("fileService enable:{}",properties.isEnable());
        logger.info("fileService upload path:{}",properties.getPath());
        logger.info("fileService domain:{}",properties.getDomain());
    }

    /**
     * 文件上传
     * @param files
     * @return
     */
    public List<FileResult> upload(MultipartFile files[]){
        List<FileResult> fileList = new ArrayList<>();
        for (MultipartFile file : files){
            //文件名称
            String originalFilename = file.getOriginalFilename();
            //调用工具类方法
            String extName = FileUtil.extName(originalFilename);
            String fileName = UUID.randomUUID()+"."+extName;
            //保存文件
            File saveFile = new File(properties.getPath(),fileName);
            try {
                file.transferTo(saveFile);
                FileResult fileResult = new FileResult(fileName,properties.getDomain(),properties.getDomain()+fileName);
                fileList.add(fileResult);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
        return fileList;
    }
}
